package com.mani.geotag;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;

public class CheckBoxView extends View{

	public interface onCheckedChange {
		void onCheckClick(View v);
	}
	boolean isTouchDown = false;
	Bitmap mTick;
	Rect  mRect;
	Rect  mRect1;
	Paint mPaint;
	public CheckBoxView(Context context) {
		super(context);
	}
	int mHeight;
	public CheckBoxView(Context context,AttributeSet attrs) {
		super(context,attrs);
		mTick = BitmapFactory.decodeResource(context.getResources(), R.drawable.tick);
		DisplayMetrics metrics = new DisplayMetrics();
    	((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
		int mHeight = metrics.heightPixels;
		if(mHeight == 320 || mHeight == 240) {
			mRect = new Rect(0,0,32,32);
			mRect1 = new Rect(0,12,25,32);
		} else {
			mRect = new Rect(0,0,48,48);
			mRect1 = new Rect(0,20,38,48);
		}
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setColor(Color.rgb(0x60,0x33,0x11));
	}
	
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
	 {  
		if(mHeight == 320 || mHeight == 240) 
			setMeasuredDimension(32,32);
		else
			setMeasuredDimension(48,48);  
	 }
	
	public boolean isChecked() {
		return isCheckDrawn;
	}
	
	public void setCheckBox(boolean draw) {
		isCheckDrawn = draw;
		invalidate();
	}
	private onCheckedChange mCB = null;
	public void setChecklistener(onCheckedChange aCB) {
		mCB = aCB;
	}
	
	int currX;
	boolean isMovementDetected = false;
	boolean isCheckDrawn = false;
	
	public boolean onTouchEvent(MotionEvent event) {
		
		int pointerX = (int) event.getX();
		int pointerY = (int) event.getY();
		switch(event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if(mRect.contains(pointerX, pointerY) == true)
					isTouchDown = true;
				break;
			case MotionEvent.ACTION_MOVE:
				currX = (int) event.getX();
				int deltaX = Math.abs(currX - pointerX);
	
				if(deltaX > ViewConfiguration.getTouchSlop())
				{
					isMovementDetected = true;
				}
					
				break;
			case MotionEvent.ACTION_UP:
				if(isMovementDetected == false && isTouchDown == true) {
					if(isCheckDrawn == false) {
						isCheckDrawn = true;
					} else {
						isCheckDrawn = false;
					}
					if(mCB != null)
						mCB.onCheckClick(this);
					invalidate();
					isTouchDown = false;
				}
				isMovementDetected = false;
				break;
		}
		return true;
	}
	
	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawRect(mRect1, mPaint);
		if(isCheckDrawn == true) {
			canvas.drawBitmap(mTick, null, mRect, null);
		}
	}
}
